package ar.vc.trans;

/* Inversa Local by @W!L */

public class Inversa1
{
    private static int[] _V;
    private static float _det;

    public static float[][] getInv(float[][] M, int n)
    {
        _V    = new int[n];
        _det  = 1.0f;
        float p;
        int i = 0;
        int j;
        int k;

        while ( ( i < n ) && ( _det != 0.0f ) )
        {
            pivot(M,i,n);
            p = M[i][i];
            M[i][i] = 1.0f;
            _det = _det*p;
            if ( p != 0.0f )
            {
                for ( j = 0; j < n; j++ )
                {
                    M[i][j] = M[i][j]/p;
                }
                for ( k = 0; k < n; k++ )
                {
                    if ( k != i )
                    {
                        p       = M[k][i];
                        M[k][i] = 0.0f;
                        for (  j = 0; j < n; j++ )
                        { M[k][j] -= p*M[i][j]; }
                    }
                }
                i += 1;
            }
        }
        if ( _det == 0 )
        {
            System.out.println(" Erro #NOT_INV \n");
            return null;
        }
        else
        {
            trocacol(M,n);
            return M;
        }   
    }

    private static void pivot(float[][] M, int i, int n)
    {
        float c = M[i][i];
        int   l = i;
        int   k;
        for ( k = i + 1; k < n; k++ )
        {
            if ( Math.abs(c) < Math.abs(M[k][i]) )
            {
                c = M[k][i];
                l = k;
            }
        }
        _V[i] = l;
        if ( l != i )
        {
            _det = -_det;
            for ( k = 0; k < n; k++ )
            {
                c       = M[i][k];
                M[i][k] = M[l][k];
                M[l][k] = c;
            }
        }
    }

    private static void trocacol(float[][] M, int n)
    {
        int i;
        int j;
        float c;
        for ( i = n-1 ; i >= 0; i-- )
        {
            if ( _V[i] != i )
            {
                for ( j = 0; j < n; j++ )
                {
                    c           = M[j][i];
                    M[j][i]     = M[j][_V[i]];
                    M[j][_V[i]] = c;
                }
            }
        }
    }
}